package com.gz.service.impl;

import com.gz.vo.LoginUser;
import com.gz.dto.TuserDto;
import com.gz.entity.Tuser;
import com.gz.service.TuserService;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TuserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TuserDto dto = new TuserDto();
        dto.setUsername(username);
        //查询用户信息
        List<Tuser> users = userService.queryAll(dto);
        Tuser user = users!=null&& !users.isEmpty()?users.stream().findFirst().get():null;
        //如果没有查询到用户就抛出异常
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //TODO 查询对应的权限信息
        //把数据封装成UserDetails返回
        return new LoginUser(user);
    }
}

